"""
项目的初始化

"""

# 项目的初始化
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from flask_wtf.csrf import CSRFProtect, generate_csrf
from config import config_mode
from config import setup_log

# 数据库
db = SQLAlchemy()
redis_store = None


# 新建一个返回app的方法
def creat_app(config_name):
    # 设置日志信息
    setup_log(config_name)

    app = Flask(__name__)

    # 从配置文件中加载信息
    app.config.from_object(config_mode[config_name])

    # 加载mysql的连接
    db.init_app(app)

    # 加载redis数据库
    global redis_store
    redis_store = StrictRedis(host=config_mode[config_name].REDIS_HOST, port=config_mode[config_name].REDIS_PORT)

    # 加载CSRF
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 加载session
    Session(app)

    # 注册过滤器
    from info.utils.htmlfilter import rank_list_class
    app.add_template_filter(rank_list_class, "rank")

    # 注册蓝图
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.user import userblu
    app.register_blueprint(userblu)

    # 注册404错误页面
    @app.errorhandler(404)
    def not_found(_):
        return render_template("404/index.html")

    print(app.url_map)

    return app
